package com.neusoft.nepb.controller;

import com.neusoft.nepb.common.AlertUtils;
import com.neusoft.nepb.common.FileUtils;
import com.neusoft.nepb.common.SceneUtils;
import com.neusoft.nepb.entity.User;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.Map;

public class UserLoginViewController {
    @FXML
    private TextField txt_phoneNumber;
    @FXML
    private TextField txt_password;
    @FXML
    private ImageView imageView;

    @FXML
    public void initialize(){
        //初始化图像
        SceneUtils.setImage(imageView,"/com/neusoft/nepb/image/sky.jpg");
    }

    public void login(ActionEvent event) throws IOException {
        Map<String, User> userMap = FileUtils.readMapObject("user.txt");
        String phoneNumber = txt_phoneNumber.getText();
        String password = txt_password.getText();
        if(userMap.containsKey(phoneNumber)) {
            User u = userMap.get(phoneNumber);
            if(password.equals(u.getPassword())) {
                //登陆成功，跳转到选择网格界面
                FXMLLoader fxmlLoader = new FXMLLoader();
                URL url = getClass().getResource("../view/SeclectNetView.fxml");
                fxmlLoader.setLocation(url);
                Parent root = fxmlLoader.load();
                Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
                Scene scene = new Scene(root);
                stage.setScene(scene);
                stage.show();
            }
            else
            {
                AlertUtils.showDialog("用户登录","登陆失败");
            }
        }else{
            AlertUtils.showDialog("用户登录","用户不存在");
        }
    }
    @FXML
    private void handleRegister(ActionEvent event) throws IOException {
        SceneUtils.switchTo(event,"/com/neusoft/nepb/view/UserRegisterView.fxml");
    }
}
